package com.wl.shixun3.controller;

import com.wl.shixun3.entity.User;
import com.wl.shixun3.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 找回密码控制器
 */
@WebServlet("/shixun3/forgotPassword")
public class ForgotPasswordController extends HttpServlet {
    private UserService userService;

    @Override
    public void init() throws ServletException {
        userService = new UserService();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 转发到找回密码页面
        request.getRequestDispatcher("/shixun3/forgotPassword.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 设置编码
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");

        // 获取操作类型
        String action = request.getParameter("action");
        
        if ("verify".equals(action)) {
            // 第一步：验证身份并显示密码
            handleVerifyIdentity(request, response);
        } else if ("changePassword".equals(action)) {
            // 第二步：修改密码
            handleChangePassword(request, response);
        } else {
            // 默认显示验证表单
            request.getRequestDispatcher("/shixun3/forgotPassword.jsp").forward(request, response);
        }
    }
    
    /**
     * 处理身份验证，验证成功后显示当前密码
     */
    private void handleVerifyIdentity(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 获取表单参数并去除前后空格
        String username = request.getParameter("username");
        String securityQuestion = request.getParameter("securityQuestion");
        String securityAnswer = request.getParameter("securityAnswer");

        // 参数验证
        if (username == null || username.trim().isEmpty() ||
            securityQuestion == null || securityQuestion.trim().isEmpty() ||
            securityAnswer == null || securityAnswer.trim().isEmpty()) {
            request.setAttribute("errorMessage", "所有字段都不能为空！");
            request.getRequestDispatcher("/shixun3/forgotPassword.jsp").forward(request, response);
            return;
        }

        // 去除前后空格
        username = username.trim();
        securityQuestion = securityQuestion.trim();
        securityAnswer = securityAnswer.trim();

        // 验证用户和安全问题
        User user = userService.getUserByUsername(username);
        
        if (user == null) {
            request.setAttribute("errorMessage", "用户名不存在！");
            request.getRequestDispatcher("/shixun3/forgotPassword.jsp").forward(request, response);
            return;
        }

        // 获取数据库中的安全问题和答案，并去除前后空格
        String dbQuestion = user.getSecurityQuestion() != null ? user.getSecurityQuestion().trim() : "";
        String dbAnswer = user.getSecurityAnswer() != null ? user.getSecurityAnswer().trim() : "";

        // 打印调试信息（帮助排查问题）
        try {
            System.out.println("========== Find Password Verification ==========");
            System.out.println("Username: " + username);
            System.out.println("Input Question Length: " + securityQuestion.length());
            System.out.println("DB Question Length: " + dbQuestion.length());
            System.out.println("Input Answer Length: " + securityAnswer.length());
            System.out.println("DB Answer Length: " + dbAnswer.length());
            System.out.println("Question Match: " + dbQuestion.equals(securityQuestion));
            System.out.println("Answer Match: " + dbAnswer.equals(securityAnswer));
            
            // 逐字符比较安全问题
            if (!dbQuestion.equals(securityQuestion)) {
                System.out.println("Question Character Comparison:");
                int minLen = Math.min(dbQuestion.length(), securityQuestion.length());
                for (int i = 0; i < minLen; i++) {
                    char c1 = dbQuestion.charAt(i);
                    char c2 = securityQuestion.charAt(i);
                    if (c1 != c2) {
                        System.out.println("  Position " + i + ": DB[" + (int)c1 + "] vs Input[" + (int)c2 + "]");
                    }
                }
            }
            System.out.println("==================================");
        } catch (Exception e) {
            System.out.println("Debug output error: " + e.getMessage());
        }

        // 验证安全问题和答案（去除空格后比较）
        // 注意：由于可能存在编码问题，我们对问号做特殊处理
        boolean questionMatch = dbQuestion.equals(securityQuestion);
        
        // 如果直接匹配失败，尝试处理问号的不同编码
        if (!questionMatch) {
            // 替换中文问号为英文问号再比较
            String dbQuestionNormalized = dbQuestion.replace('？', '?').replace('?', '？');
            String inputQuestionNormalized = securityQuestion.replace('？', '?').replace('?', '？');
            questionMatch = dbQuestionNormalized.equals(inputQuestionNormalized) || 
                           dbQuestion.replace('？', '?').equals(securityQuestion.replace('？', '?'));
        }
        
        boolean answerMatch = dbAnswer.equals(securityAnswer);
        
        if (!questionMatch || !answerMatch) {
            String errorDetail = "";
            if (!questionMatch) errorDetail += "安全问题不匹配。";
            if (!answerMatch) errorDetail += "安全答案不匹配。";
            request.setAttribute("errorMessage", "安全问题或答案不正确！" + errorDetail);
            request.getRequestDispatcher("/shixun3/forgotPassword.jsp").forward(request, response);
            return;
        }

        // 验证成功，显示当前密码
        request.setAttribute("currentPassword", user.getPassword());
        request.setAttribute("verifiedUsername", username);
        request.getRequestDispatcher("/shixun3/forgotPassword.jsp").forward(request, response);
    }
    
    /**
     * 处理修改密码
     */
    private void handleChangePassword(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 获取表单参数
        String username = request.getParameter("username");
        String newPassword = request.getParameter("newPassword");
        String confirmPassword = request.getParameter("confirmPassword");

        // 参数验证
        if (username == null || username.trim().isEmpty() ||
            newPassword == null || newPassword.trim().isEmpty() ||
            confirmPassword == null || confirmPassword.trim().isEmpty()) {
            request.setAttribute("errorMessage", "所有字段都不能为空！");
            request.getRequestDispatcher("/shixun3/forgotPassword.jsp").forward(request, response);
            return;
        }

        // 验证两次密码是否一致
        if (!newPassword.equals(confirmPassword)) {
            request.setAttribute("errorMessage", "两次输入的密码不一致！");
            // 保留验证信息，重新显示密码
            User user = userService.getUserByUsername(username);
            if (user != null) {
                request.setAttribute("currentPassword", user.getPassword());
                request.setAttribute("verifiedUsername", username);
            }
            request.getRequestDispatcher("/shixun3/forgotPassword.jsp").forward(request, response);
            return;
        }

        // 更新密码
        boolean success = userService.updatePassword(username, newPassword);
        
        if (success) {
            request.setAttribute("successMessage", "密码修改成功！请使用新密码登录。");
            request.getRequestDispatcher("/shixun3/resetSuccess.jsp").forward(request, response);
        } else {
            request.setAttribute("errorMessage", "密码修改失败，请稍后再试！");
            // 保留验证信息
            User user = userService.getUserByUsername(username);
            if (user != null) {
                request.setAttribute("currentPassword", user.getPassword());
                request.setAttribute("verifiedUsername", username);
            }
            request.getRequestDispatcher("/shixun3/forgotPassword.jsp").forward(request, response);
        }
    }
}

